package com.jackykeke.fiveplussdkdemo;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.jackykeke.HBuilder.integrate.SDK_WebApp;
import com.jackykeke.camera.CameraManager;
import com.jackykeke.tools.BeepManager;
import com.jackykeke.tools.CaptureActivityHandler;
import com.jackykeke.tools.DecodeThread;
import com.jackykeke.tools.InactivityTimer;
import com.jackykeke.tools.ScanningImageTools;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.dcloud.EntryProxy;


/**
 * Created by Jacky F1233804 on 2018/7/17
 * desc：
 */

public class ScanActivity extends AppCompatActivity implements SurfaceHolder.Callback {

    private static final String TAG = ScanActivity.class.getSimpleName();

    private CameraManager cameraManager;
    /**
     * CaptureActivityHandler
     */
    private CaptureActivityHandler handler;
    /**
     * 定时关闭长时间未使用的activity
     */
    private InactivityTimer inactivityTimer;
    /**
     * 震动
     */
    private BeepManager beepManager;
    /**
     * SurfaceView
     */
    private SurfaceView scanPreview = null;
    private RelativeLayout scanContainer;
    /**
     * 扫描框
     */
    private RelativeLayout scanCropView;
    /**
     * 扫描线
     */
    private ImageView scanLine;
    private TranslateAnimation animation;
    String photo_path = "";
    Bitmap scanBitmap;
    Button caputer_back, btn_rescan, btn_photo;
    protected TextView title, capture_mask_top, tv_scan_result;

    private Rect mCropRect = null;

    private static final int REQUEST_CODE = 110;

    public MediaPlayer music;
    private Context context;
    private BroadcastReceiver UnzipWebAppReceiver;
    private ProgressDialog pDialog;
    private EntryProxy mEntryProxy;
    private int mode;

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    private boolean isHasSurface = false;

//    UrlUtil UrlUtil = new UrlUtil();

    private String heart = "";

    private String report = "";

    private boolean circleScan = false;


    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capture_main);
        context = ScanActivity.this;
        mode = getIntent().getIntExtra("mode", 0);
        initCaptureView();


    }


    private void initCaptureView() {

        caputer_back = (Button) findViewById(R.id.btn_back);
        title = (TextView) findViewById(R.id.title);
        tv_scan_result = (TextView) findViewById(R.id.tv_scan_result);
        capture_mask_top = (TextView) findViewById(R.id.capture_mask_top);// 扫一扫
        title.setText("扫一扫");
        caputer_back = (Button) findViewById(R.id.btn_back);
        btn_photo = (Button) findViewById(R.id.btn_photo);
        btn_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                selectQCoder();

            }
        });
        btn_rescan = (Button) findViewById(R.id.btn_rescan);
        caputer_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        btn_rescan.setOnClickListener(new View.OnClickListener() {// 重新扫描

            @Override
            public void onClick(View v) {
                reScan(500);
            }
        });
        scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
        scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
        scanLine = (ImageView) findViewById(R.id.capture_scan_line);
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);

        /**
         * 扫描线动画
         */
        animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.98f);
        animation.setDuration(4500);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.RESTART);
        scanLine.startAnimation(animation);

    }

    private void reScan(long delayMS) {
        restartPreviewAfterDelay(delayMS);
        capture_mask_top.setText("正在扫描...");
        if (animation != null) {
            animation.start();
        }

    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
        if (animation != null) {
            scanLine.startAnimation(animation);
        }
    }


    protected void onResume() {
        super.onResume();
        if (cameraManager == null) {

            cameraManager = new CameraManager(getApplication());
        }

        if (isHasSurface) {
            initCamera(scanPreview.getHolder());
        } else {
            scanPreview.getHolder().addCallback(this);
        }

        inactivityTimer.onResume();
    }

    @Override
    public void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!isHasSurface) {
            scanPreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (scanPreview != null) {

            scanPreview.getHolder().removeCallback(this);
        }

        inactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            // L.e(TAG, "*** WARNING *** surfaceCreated() gave us a null
            // surface!");
        }
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }


    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            // L.w(TAG, "initCamera() while already open -- late SurfaceView
            // callback?");
            return;
        }

        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
            }

            initCrop();
        } catch (IOException ioe) {
            // L.w(TAG, ioe.toString());
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            // L.w(TAG, "Unexpected error initializing camera");
            displayFrameworkBugMessageAndExit();
        }
    }

    @SuppressLint("NewApi")
    private void displayFrameworkBugMessageAndExit() {
        // camera error
        AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage("相机权限，请到系统设置开启" + getString(R.string.app_name) + "相机访问权限");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }

        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
                finish();
            }
        });
        builder.show();
    }

    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;

        /** 获取布局中扫描框的位置信息 */
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1] - getStatusBarHeight();

        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();

        /** 获取布局容器的宽高 */
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();

        /** 计算最终截取的矩形的左上角顶点x坐标 */
        int x = cropLeft * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的左上角顶点y坐标 */
        int y = cropTop * cameraHeight / containerHeight;

        /** 计算最终截取的矩形的宽度 */
        int width = cropWidth * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的高度 */
        int height = cropHeight * cameraHeight / containerHeight;

        /** 生成最终的截取的矩形 */
        mCropRect = new Rect(x, y, width + x, height + y);
    }

    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 扫描成功在 CaptureActivityHandler 中调用 时间：2016年6月14日
     */
    public void handleDecode(Result rawResult, Bundle bundle) {
        capture_mask_top.setText("扫描完成");
        animation.cancel();
        if (rawResult != null) {
            inactivityTimer.onActivity();
            beepManager.playBeepSoundAndVibrate();
            final String recode = ScanningImageTools.recode(rawResult.toString());
            doResult(recode);
        } else {// 未识别到二维码重新扫描
//            T.showShort(AtyCapture.this, "未识别到二维码");
            Toast.makeText(ScanActivity.this, "未识别到二维码", Toast.LENGTH_SHORT).show();
            restartPreviewAfterDelay(500);
            capture_mask_top.setText("正在扫描...");
            tv_scan_result.setText(getResources().getString(R.string.scan_tips));
        }

    }

    /**
     * 处理非空二维码
     *
     * @param result
     */
    public void doResult(String result) {

        Intent intent = new Intent(ScanActivity.this, SDK_WebApp.class);
        intent.putExtra("web", result);
        intent.putExtra("mode", mode);
        startActivity(intent);
        finish();

        String appName = "iportal:";
        String myQrcode = "";
        if (!TextUtils.isEmpty(result) && result.length() > appName.length()) {
            Boolean flag = result.substring(0, appName.length()).equals(appName);
            if (flag) {// 是爱口袋二维码，检测二维码的有效性
//                try {
//                    myQrcode = result.replace(appName, "").toString().trim();
////                    if (getNetworkstate()) {
//
                CheckIsValidQrcode(myQrcode);
//
////                    } else {
////                        startActivity(new Intent(AtyCapture.this, AtyScanResultTxt.class)
////                                .putExtra(AtyScanResultTxt.FLAG, AtyScanResultTxt.ERROR_NETWORK));
////                        finish();
////                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
            } else if (result.substring(0, 6).equals("circle")) {
//                String decodeStr = AppUtil.getDecodeStr(result.substring(6, result.length()));
//                String groupId = decodeStr.substring(0, decodeStr.indexOf(":"));
//                decodeStr = decodeStr.substring(decodeStr.indexOf(":") + 1);
//                String groupName = decodeStr.substring(0, decodeStr.indexOf(":"));
//                decodeStr = decodeStr.substring(decodeStr.indexOf(":") + 1);
//                String groupSize = decodeStr.substring(0, decodeStr.indexOf(":"));
//                String isAlter = decodeStr.substring(decodeStr.indexOf(":") + 1);
//                confirm(groupId, groupName, groupSize, isAlter);
            } else {// 不是爱口袋二维码
//                myQrcode = result;
//                if (isUrl(myQrcode)) {
//                    L.d("webUrlmyQrcode===", myQrcode);
////					Intent intent = new Intent(AtyCapture.this, AtyScanResultHtml.class);
////					intent.putExtra("SCAN_RESULT", myQrcode);
//                    Intent intent = new Intent(AtyCapture.this, AtyWebView02.class);
//                    GridViewItemInfo gridViewItemInfo = new GridViewItemInfo();
////					gridViewItemInfo.setFlag(1);// 不需要工号
////					gridViewItemInfo.setMenuName(eventArgs.get(1).getNextAction());
//                    gridViewItemInfo.setWebURL(myQrcode);
//                    intent.putExtra(AppContants.WEBVIEW.ITEMINFO, gridViewItemInfo);
//                    startActivity(intent);
//                    finish();
//                } else {
//                    if (report != null && report.equals("Report")) {
//                        setResult(11, new Intent().putExtra("SCAN_RESULT", myQrcode));
//                        finish();
//                    } else {
//                        Intent intent = new Intent(AtyCapture.this, AtyScanResultTxt.class);
//                        intent.putExtra("SCAN_RESULT", myQrcode);
//                        intent.putExtra(AtyScanResultTxt.FLAG, AtyScanResultTxt.OK);
//                        startActivity(intent);
//                        finish();
//                    }
//
//                }
            }
        } else {// 字符串长度小于标识符长度
            myQrcode = result;
//            Intent intent = new Intent(AtyCapture.this, AtyScanResultTxt.class);
//            intent.putExtra("SCAN_RESULT", myQrcode);
//            intent.putExtra(AtyScanResultTxt.FLAG, AtyScanResultTxt.OK);
//            startActivity(intent);
            finish();
        }
    }

    protected ExecutorService executorService = Executors.newFixedThreadPool(20);

    /**
     * <li>描述：扫一扫统一整合
     * <li>时间：2016年9月27日
     * <li>author： H2601977
     */
    private void CheckIsValidQrcode(final String qrcode) {
        executorService.submit(new Runnable() {

            @Override
            public void run() {
                @SuppressWarnings("deprecation")
//                String url = String.format(new UrlUtil().SCAN, URLEncoder.encode(AppUtil.getIMEIByAes(ScanActivity.this)),
//                        URLEncoder.encode(AppUtil.getStrByAES(app.getSysUserID())), URLEncoder.encode(qrcode),
//                        URLEncoder.encode(AppUtil.getStrByAES("Android")));
//
//                JsonAccount jsonAccount = new JsonAccount();
//                ScanQrcodeResult result = jsonAccount.getScanResult(url);
////                L.d("ScanQrcodeResult===", result.toString());
//                if (result != null) {
//                    Looper.prepare();
//                    if (result.getIsOk().equals("1")) {
//                        try {
//                            ArrayList<CommonResult> eventArgs = result.getEventArgs();
//                            if (null != eventArgs && eventArgs.size() > 0) {
//                                if ("W".equals(result.getEventType())) {// web页面
//                                    L.d("webUrl===", result.getEventType());
//                                    String webUrl = eventArgs.get(0).getNextAction();
//                                    // webUrl=AppUtil.getAuthWebUrl(webUrl);
//                                    Intent intent = new Intent(AtyCapture.this, AtyWebView02.class);
//                                    GridViewItemInfo gridViewItemInfo = new GridViewItemInfo();
//                                    gridViewItemInfo.setFlag(1);// 不需要工号
//                                    gridViewItemInfo.setMenuName(eventArgs.get(1).getNextAction());
//                                    gridViewItemInfo.setWebURL(webUrl);
//                                    intent.putExtra(AppContants.WEBVIEW.ITEMINFO, gridViewItemInfo);
//                                    startActivity(intent);
//                                    finish();
//                                } else if ("N".equals(result.getEventType())) {// native
//                                    if (!TextUtils.isEmpty(result.getParam())) {
//                                        String[] Params = result.getParam().split(",");
//                                        if (Params[0].equals("Invalid")) {
//                                            startActivity(new Intent(AtyCapture.this, AtyScanResultTxt.class)
//                                                    .putExtra(AtyScanResultTxt.FLAG, AtyScanResultTxt.INVALID));
//                                            finish();
//                                        } else if (Params[0].equals("Valid")) {
//                                            if (heart != null && heart.equals("heart")) {
//                                                setResult(11, new Intent().putExtra("USERNO", Params[1]));
//                                                finish();
//                                            } else {
//                                                Intent intent = new Intent();
//                                                Class<?> cls = AppUtil.classNameToClass(eventArgs.get(0).getNextAction());
//                                                intent.setClass(AtyCapture.this, cls);
//                                                if (eventArgs.get(0).getNextAction()
//                                                        .equals("com.foxconn.iportal.zxing.aty.AtyMyQRCodeDetailInfo")) {
//                                                    intent.putExtra("USER_ID", Params[1]);
//                                                    intent.putExtra("USER_NAME", Params[2]);
//                                                    intent.putExtra("DEPT", Params[3]);
//                                                }
//                                                intent.putExtra("PUBLIC_PARAM", result.getParam());
//                                                startActivity(intent);
//                                                finish();
//                                            }
//                                        }
//
//                                    }
//                                } else if ("M".equals(result.getEventType())) {// sound
//                                    // 或者
//                                    // 消息
//                                    String args0 = "";
//                                    String args1 = "";// 是否重新扫描
//                                    String args2 = "";// 文字
//                                    String args3 = "";// 声音
//                                    for (int i = 0; i < eventArgs.size(); i++) {// 数组长度不确定
//                                        if (i == 0) {
//                                            args0 = eventArgs.get(0).getNextAction();
//                                        } else if (i == 1) {
//                                            args1 = eventArgs.get(1).getNextAction();
//                                        } else if (i == 2) {
//                                            args2 = eventArgs.get(2).getNextAction();
//                                        } else if (i == 3) {
//                                            args3 = eventArgs.get(3).getNextAction();
//                                        }
//                                    }
//                                    if ("W".equals(args0)) {// message显示word
//                                        T.showShort(AtyCapture.this, args2);
//                                    } else if ("S".equals(args0)) {// 声音
//                                        if ("S".equals(args3)) {// 成功的声音
//                                            startMusic(R.raw.micro_class_ok);
//                                        } else {// 失败的声音
//                                            startMusic(R.raw.micro_class_error);
//                                        }
//                                    } else if ("WS".equals(args0)) {// 消息+声音
//                                        if ("S".equals(args3)) {// 成功的声音
//                                            startMusic(R.raw.micro_class_ok);
//                                        } else {// 失败的声音
//                                            startMusic(R.raw.micro_class_error);
//                                        }
//                                        if (!TextUtils.isEmpty(args2)) {
//                                            T.showShort(AtyCapture.this, args2);
//                                        }
//                                    }
//                                    if ("Y".equals(args1)) {
//                                        reScan(600);
//                                    } else {
//                                        finish();
//                                        Looper.loop();
//                                    }
//                                } else {
//
//                                }
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//
//                    } else if (result.getIsOk().equals("0")) {
//                        T.showShort(AtyCapture.this, result.getMsg());
//                    }
//                    Looper.loop();
//                } else {
//                    Looper.prepare();
//                    startActivity(new Intent(AtyCapture.this, AtyScanResultTxt.class).putExtra(AtyScanResultTxt.FLAG,
//                            AtyScanResultTxt.ERROR));
//                    finish();
//                    Looper.loop();
//                }


                        Intent intent = new Intent(ScanActivity.this, SDK_WebApp.class);
                intent.putExtra("web", "");
                startActivity(intent);

                // 去拉取zip
                /**
                 * start WebAppService  动态下载网页
                 */


            }
        });

    }


    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }


    public Rect getCropRect() {
        return mCropRect;
    }

}
